// 通用JavaScript函数

// 配置axios
axios.defaults.baseURL = '';

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers.Authorization = token;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(
    function (response) {
        return response;
    },
    function (error) {
        if (error.response && error.response.status === 401) {
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            window.location.href = '/login';
        }
        return Promise.reject(error);
    }
);

// 通用工具函数
const Utils = {
    // 格式化日期
    formatDate: function(date, format = 'YYYY-MM-DD') {
        if (!date) return '';
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        
        return format
            .replace('YYYY', year)
            .replace('MM', month)
            .replace('DD', day)
            .replace('HH', hours)
            .replace('mm', minutes)
            .replace('ss', seconds);
    },
    
    // 格式化日期时间
    formatDateTime: function(date) {
        return this.formatDate(date, 'YYYY-MM-DD HH:mm:ss');
    },
    
    // 显示加载状态
    showLoading: function(element) {
        if (element) {
            element.innerHTML = '<div class="loading"></div> 加载中...';
        }
    },
    
    // 隐藏加载状态
    hideLoading: function(element, originalContent) {
        if (element) {
            element.innerHTML = originalContent || '';
        }
    },
    
    // 显示成功消息
    showSuccess: function(message) {
        this.showAlert(message, 'success');
    },
    
    // 显示错误消息
    showError: function(message) {
        this.showAlert(message, 'danger');
    },
    
    // 显示警告消息
    showWarning: function(message) {
        this.showAlert(message, 'warning');
    },
    
    // 显示信息消息
    showInfo: function(message) {
        this.showAlert(message, 'info');
    },
    
    // 显示警告框
    showAlert: function(message, type = 'info') {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        // 插入到页面顶部
        const container = document.querySelector('.main-content') || document.body;
        container.insertBefore(alertDiv, container.firstChild);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 3000);
    },
    
    // 确认对话框
    confirm: function(message, callback) {
        if (confirm(message)) {
            if (typeof callback === 'function') {
                callback();
            }
            return true;
        }
        return false;
    },
    
    // 获取URL参数
    getUrlParam: function(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    },
    
    // 设置URL参数
    setUrlParam: function(name, value) {
        const url = new URL(window.location);
        url.searchParams.set(name, value);
        window.history.pushState({}, '', url);
    },
    
    // 验证手机号
    validatePhone: function(phone) {
        const phoneRegex = /^1[3-9]\d{9}$/;
        return phoneRegex.test(phone);
    },
    
    // 验证身份证号
    validateIdCard: function(idCard) {
        const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        return idCardRegex.test(idCard);
    },
    
    // 验证邮箱
    validateEmail: function(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    },
    
    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};

// 用户相关函数
const User = {
    // 获取当前用户信息
    getCurrentUser: function() {
        const userInfo = localStorage.getItem('userInfo');
        return userInfo ? JSON.parse(userInfo) : null;
    },
    
    // 获取当前用户ID
    getCurrentUserId: function() {
        const user = this.getCurrentUser();
        return user ? user.id : null;
    },
    
    // 获取当前用户角色
    getCurrentUserRole: function() {
        const user = this.getCurrentUser();
        return user ? user.uRole : null;
    },
    
    // 检查是否为管理员
    isAdmin: function() {
        return this.getCurrentUserRole() === 1;
    },
    
    // 检查是否为医生
    isDoctor: function() {
        return this.getCurrentUserRole() === 2;
    },
    
    // 检查是否为患者
    isPatient: function() {
        return this.getCurrentUserRole() === 3;
    },
    
    // 退出登录
    logout: function() {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        window.location.href = '/login';
    }
};

// 页面导航相关函数
const Navigation = {
    // 显示指定内容区域
    showSection: function(sectionId) {
        // 隐藏所有内容区域
        const sections = document.querySelectorAll('.content-section');
        sections.forEach(section => {
            section.style.display = 'none';
        });
        
        // 显示指定区域
        const targetSection = document.getElementById(sectionId);
        if (targetSection) {
            targetSection.style.display = 'block';
            targetSection.classList.add('fade-in');
        }
    },
    
    // 更新活跃导航
    updateActiveNav: function(activeId) {
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.classList.remove('active');
        });
        
        // 根据activeId设置对应的导航为活跃状态
        const activeLink = document.querySelector(`[onclick*="${activeId}"]`);
        if (activeLink) {
            activeLink.classList.add('active');
        }
    }
};

// 表格相关函数
const Table = {
    // 创建空数据行
    createEmptyRow: function(colspan, message = '暂无数据') {
        return `<tr><td colspan="${colspan}" class="text-center text-muted">${message}</td></tr>`;
    },
    
    // 创建加载行
    createLoadingRow: function(colspan) {
        return `<tr><td colspan="${colspan}" class="text-center"><div class="loading"></div> 加载中...</td></tr>`;
    },
    
    // 创建操作按钮
    createActionButtons: function(actions) {
        let buttons = '';
        actions.forEach(action => {
            const icon = action.icon ? `<i class="${action.icon} me-1"></i>` : '';
            buttons += `<button class="btn btn-sm ${action.class} btn-action" onclick="${action.onclick}">${icon}${action.text}</button>`;
        });
        return buttons;
    }
};

// 模态框相关函数
const Modal = {
    // 显示模态框
    show: function(modalId) {
        const modal = new bootstrap.Modal(document.getElementById(modalId));
        modal.show();
        return modal;
    },
    
    // 隐藏模态框
    hide: function(modalId) {
        const modal = bootstrap.Modal.getInstance(document.getElementById(modalId));
        if (modal) {
            modal.hide();
        }
    },
    
    // 重置表单
    resetForm: function(formId) {
        const form = document.getElementById(formId);
        if (form) {
            form.reset();
        }
    }
};

// 表单验证相关函数
const FormValidation = {
    // 验证必填字段
    validateRequired: function(fields) {
        let isValid = true;
        fields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field && !field.value.trim()) {
                field.classList.add('is-invalid');
                isValid = false;
            } else if (field) {
                field.classList.remove('is-invalid');
            }
        });
        return isValid;
    },
    
    // 验证手机号
    validatePhoneField: function(fieldId) {
        const field = document.getElementById(fieldId);
        if (field && !Utils.validatePhone(field.value)) {
            field.classList.add('is-invalid');
            return false;
        } else if (field) {
            field.classList.remove('is-invalid');
        }
        return true;
    },
    
    // 验证身份证号
    validateIdCardField: function(fieldId) {
        const field = document.getElementById(fieldId);
        if (field && !Utils.validateIdCard(field.value)) {
            field.classList.add('is-invalid');
            return false;
        } else if (field) {
            field.classList.remove('is-invalid');
        }
        return true;
    }
};

// 导出到全局作用域
window.Utils = Utils;
window.User = User;
window.Navigation = Navigation;
window.Table = Table;
window.Modal = Modal;
window.FormValidation = FormValidation;
